<?php
/**
 * IG_Acl
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Acl.php 1140 2012-01-10 01:10:23Z mmxie $
 */
class IG_Acl extends Zend_Acl
{
    /**
     * @var IG_Acl
     */
    private static $_instance = null;

    public function __construct()
    {
        $this->loadPremission();
    }

    /**
     * 注册资源、角色，以及角色授权
     */
    public function loadPremission()
    {
        $roleModel  = new System_Model_Role();

        foreach ($roleModel->fetchAll() as $role) {
            if (!$this->hasRole($role->getName())) {
                if ($role->getName() == 'guest') {
                    $this->addRole($role->getName());
                } else if ($role->getName() == 'base') {
                    $this->addRole($role->getName(), 'guest');
                } else {
                    $this->addRole($role->getName(), 'base');
                }
                foreach ($role->getResources() as $resource) {
                    if ($resource->getAction() == null) continue;

                    $resourceId = $resource->getModule() . '_'
                                . $resource->getController() . '_'
                                . $resource->getAction();

                    if (!$this->has($resourceId)) {
                        $this->add(new Zend_Acl_Resource($resourceId));
                    }

                    if ($resource->getParam() != null) {
                        $params = explode(',', $resource->getParam());
                        $this->allow($role->getName(), $resourceId, null,
                                     new IG_Acl_Assert_Param($resource->getResourceId(),
                                                             $role->getRoleId(),
                                                             $params));
                    } else {
                        $this->allow($role->getName(), $resourceId);
                    }
                }
            }
        }
    }

    /**
     *
     * @return IG_Acl
     */
    public static function getInstance()
    {
        if (self::$_instance == null) {
            $cache = Zend_Registry::get('lvan_cache');
            if (null == ($acl = $cache->load(__CLASS__))) {
                self::$_instance = new IG_Acl();
                $cache->save(self::$_instance, __CLASS__);
            } else {
                self::$_instance = $acl;
            }
        }
        return self::$_instance;
    }
}